// uploadavatar.js
const UTIL = require('../../../utils/util.js');
const qiniuUploader = require('../../../utils/qiniuUploader.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shouldSave: true,
    uptoken: '',
    imgs: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.request({
      url: 'https://www.zuihuiyou.cc/token/avatar',
      success: (res) => {
        this.setData({
          uptoken: res.data
        });
      },
      fail: function (err) {
        wx.showModal({
          title: '图片上载token获取失败，请重新打开小程序，并联系Mr. Dev',
          content: '',
          showCancel: false
        });
        console.log(err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      imgs: UTIL.Login.getImgs().length == 0 ? [] : UTIL.Login.getImgs()
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (!UTIL.Login.getIsAvatarSaved()) {
      this.setData({
        imgs: []
      });
      UTIL.Login.setImgs([]);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "游侠注册，就找最会游，专业、认真、靠谱",
      path: "/pages/index/index"
    }
  },

  upload: function() {
    let that = this;
    UTIL.Login.setImgs(that.data.imgs);
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '图片上载中，耐心等候'
        });
        Array.from(tempFilePaths).forEach(function(tPath) {
          qiniuUploader.upload(tPath, (res) => {
            that.data.imgs.push({
              imgurl_621: 'https://' + res.imageURL + '?imageView2/1/w/360/h/360/format/jpg/',
              isHeadImg: false
            });
            that.setData({
              imgs: that.data.imgs
            });
            wx.hideLoading();
          },
            (err) => {
              wx.showToast({
                title: err || '图片上传出错',
              });
              wx.hideLoading();
            },
            {
              region: 'ECN',
              domain: 'icon.zuihuiyou.cn',
              uptoken: that.data.uptoken
            });
        });
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  imgOperator: function(e) {
    let that = this;
    let imgIdx = e.target.dataset.idx;
    wx.showActionSheet({
      itemList: ['查看大图', '设为个人主页头图', '删除'],
      success: function(res) {
        switch (res.tapIndex) {
          case 0:
            UTIL.Login.setImgs(that.data.imgs);
            wx.previewImage({
              current: that.data.imgs[res.tapIndex].imgurl_621,
              urls: that.data.imgs.map(function(img) {
                return img.imgurl_621;
              })
            });
            break;
          case 1:
            that.data.imgs.forEach(function(img) {
              img.isHeadImg = false;
            });
            that.data.imgs[imgIdx].isHeadImg = true;
            that.setData({
              imgs: that.data.imgs
            });
            break;
          case 2:
            that.data.imgs.splice(imgIdx, 1);
            that.setData({
              imgs: that.data.imgs
            });
            break;  
          default:
            break; 
        }
        /*that.setData({
          imgs: that.data.imgs
        });*/
      },
      fail: function(res) {
        console.log(res.errMsg);
      }
    })
  },

  done: function() {
    UTIL.Login.setImgs(this.data.imgs);
    UTIL.Login.setIsAvatarSaved(true);
    wx.navigateBack({
      delta: 1
    });
  }
})